﻿using Lg.Core;
using Lg.Core.Exceptions;
using Lg.Core.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Survey.Web.Filters
{
    public class ExceptionCatchAttribute : Attribute, IExceptionFilter
    {
        string? errUrl = null;
        public ExceptionCatchAttribute(string? errUrl=null)
        {
            this.errUrl = errUrl;
        }

        public void OnException(ExceptionContext context)
        {
            RtMsg rtmsg = new RtMsg() { code = 100, msg = context.Exception.Message };
            if (!context.ExceptionHandled)
            {
                if (context.ExceptionDispatchInfo?.SourceException.GetType() != typeof(LgException))
                {
                    rtmsg.code = 400;
                    Log.Error("异常", $"message:{context.Exception.Message};source:{context.Exception.Source};StackTrace:{context.Exception.StackTrace }");
                    
                }
                if(errUrl != null)
                {
                    context.Result= new RedirectResult(errUrl);
                }
                else
                {
                    context.Result = new ContentResult() {  Content = rtmsg.ToJsonString()};
                }
                context.ExceptionHandled = true;
            }  
        }
    }
}
